# -*- coding: utf-8 -*-

# Podboy -- A podcast aggregator/player
#
# Copyright (C) 2009-2012 Valéry Febvre <vfebvre@easter-eggs.com>
# http://code.google.com/p/podboy/
#
# This file is part of Podboy.
#
# Podboy is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Podboy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import dbus, e_dbus

class PodboyDBus(object):
    def __init__(self, call_status_cb):
        self.loop     = e_dbus.DBusEcoreMainLoop()
        self.sysbus   = dbus.SystemBus(mainloop = self.loop)
        self.dbus_obj = None

        self.call_status_cb = call_status_cb
        self.suspend_mode   = None

        # freesmartphone Usage
        try:
            self.dbus_obj = dbus.Interface(
                self.sysbus.get_object("org.freesmartphone.ousaged", "/org/freesmartphone/Usage"),
                "org.freesmartphone.Usage")
        except Exception, e:
            print "dbus error: %s" % e
            # phonefso Usage
            try:
                self.dbus_obj = dbus.Interface(
                    self.sysbus.get_object("org.shr.phonefso.Usage", "/org/shr/phonefso/Usage"),
                    "org.shr.phonefso.Usage")
            except Exception, e:
                print "dbus error: %s" % e

        # add lsitener for GSM events (incoming, active, outgoing)
        try:
            self.sysbus.add_signal_receiver(
                self._on_call_status_received,
                dbus_interface = "org.freesmartphone.GSM.Call",
                signal_name    = "CallStatus",
                path           = "/org/freesmartphone/GSM/Device",
                bus_name       = "org.freesmartphone.ogsmd")
        except Exception, e:
            print "Failed to add listener for GSM events: %s" % e

    def _on_call_status_received(self, id, status, props):
        print "Phone call status changed to: %s." % status

        if status == "outgoing" or status == "active" or status == "incoming":
            self.call_status_cb()

    def get_bluetooth_state(self):
        return self.dbus_obj.GetResourceState("Bluetooth")

    def list_bluetooth_devices(self):
        try:
            manager = dbus.Interface(
                self.sysbus.get_object("org.bluez", "/"), "org.bluez.Manager")
            adapter = dbus.Interface(
                self.sysbus.get_object("org.bluez", manager.DefaultAdapter()), "org.bluez.Adapter")
            l = []
            for path in adapter.ListDevices():
                props = dbus.Interface(self.sysbus.get_object("org.bluez", path), "org.bluez.Device").GetProperties()
                l.append({'name': str(props.get('Name')), 'addr': str(props.get('Address'))})
            return l
        except Exception:
            return None

    def set_suspend_mode(self, mode):
        if not self.dbus_obj:
            return

        if self.suspend_mode == mode:
            print 'suspend mode is already', mode
            return
        if mode:
            print 'Release CPU resource'
            self.dbus_obj.ReleaseResource('CPU')
        else:
            print 'Request CPU resource'
            self.dbus_obj.RequestResource('CPU')
        self.suspend_mode = mode
